<template>

  <div class="container">
    <div class="card1">
      <div class="title">二维码生成</div>
      <div class="lcontainer">
        <div class="qrleft">
          <div style="font-size: 14px;">二维码信息</div>
          <div style="font-size: 12px;margin-bottom: 5px;margin-top: 20px;text-align: left;">二维码内容</div>
          <textarea placeholder="请输入二维码内容" rows="4" id="qrInfo" v-model="qrInfo" :disabled="isEdit"
            style="width: 100%;background: #F2F3F5;border: none;font-size: 12px;margin-bottom: 15px;padding: 10px;margin-top: 10px;"></textarea>
          <br />
          <!-- <div style="font-size: 12px;">纠错等级</div>
          <select v-model="selectedLevel" id="qrLevel" :disabled="isEdit"
            style="width: 40%;background: #F2F3F5;border: none;font-size: 12px;height: 28px;margin-bottom: 15px;">
            <option value="L">L(7%)</option>
            <option value="M">M(15%)</option>
            <option value="Q">Q(25%)</option>
            <option value="H">H(30%)</option>
          </select> -->
          <div style="display: flex;align-items: center;">
            <div style="display: flex;align-items: center;">
              <label>前景色：</label>
              <input type="color" id="foreground" v-model="foregroundColor" @change="colorChange" />
            </div>
            <div style="display: flex;align-items: center;margin-left: 30px;">
              <label>背景色：</label>
              <input type="color" id="background" v-model="backgroundColor" @change="colorChange" />
            </div>
            <div style="display: flex;align-items: center;margin-left: 30px;">
              <label>对比度：</label>
              <label for="background">{{ contrastInfo }}</label>
            </div>
          </div>
          <div style="display: flex;align-items: center;margin-top: 30px;">
            <div style="display: flex;align-items: center;">
              <label for="foreground">宽度：</label>
              <input type="range" id="foreground" v-model="widthSize" @change="sizeChange" min="30" max="260" />
              <label for="foreground" style="width: 30px;">{{ widthSize }}</label>
            </div>
            <div style="display: flex;align-items: center;margin-left: 30px;">
              <label for="background">高度：</label>
              <input type="range" id="background" v-model="heightSize" @change="sizeChange" min="30" max="260" />
              <label for="foreground" style="width: 30px;">{{ heightSize }}</label>
            </div>
            <div style="display: flex;align-items: center;margin-left: 30px;">
              <label for="background">对比度：</label>
              <label for="background">{{ sizeContrast }}</label>
            </div>
          </div>
          <br />
        </div>
        <div class="qright">
          <div
            style="width: 260px;height: 260px;display: flex;justify-content: center;align-items: center;border: 1px solid #ccc;">
            <img ref="myImg" :src="qrCodeUrl" :width="widthSize + 'px'" :height="heightSize + 'px'" v-if="qrCodeUrl">
          </div>
          <div style="display: flex;justify-content: space-between;width: 50%;">
            <MButton @click="save" type="submit" style="width: 50px;">保存</MButton>
            <MButton @click="validateQRCode" type="submit" style="width: 50px;">生成</MButton>
          </div>
        </div>
      </div>
      <div style="background: #F4F4F4; padding: 10px;">
        <div class="title">二维码生成列表</div>
        <div style="min-height: 370px;">
          <div style="display: flex;justify-content: left;;flex-wrap: wrap;">
            <div v-for="(qr, index) in qrList" :key="index"
              style="width: 30%;background: white;padding: 10px;margin: 10px;height: 55%;border-radius: 5px;">
              <div>
                <div style="display: flex;">
                  <div
                    style="flex:1 1 100px;width: 100px;height: 100px;display: flex;align-items: center;justify-content: center;">
                    <img :src="qr.url" alt="二维码" style="max-height: 100%;max-width:100px;" />
                  </div>
                  <div style="flex:1 1 200px;padding: 10px;text-align: left;">
                    <div style="font-size: 14px;color: #86909C;">内容</div>
                    <div class="listinfo">
                      {{ qr.info }}
                    </div>
                  </div>
                </div>
                <div style="display: flex;margin-top: 5px;">
                  <div style="flex: 1 1 100px;width: 100px;color: #86909C;text-align: left;">
                    色彩对比度:
                    <span style="color: black;">{{ qr.colorRatio }}
                    </span>
                  </div>
                  <div style="flex: 1 1 100px; color: #86909C;text-align: left;">
                    宽高对比度:
                    <span style="color: black;">{{ qr.whRatio }}
                    </span>
                  </div>
                </div>
              </div>
              <div style="text-align: right;margin-top: 10px;padding-right: 10px;display: flex;">
                <div style="flex: 1 1 100px;">
                  <div :class="qr.state" v-if="qr.state != ''">
                    <img :src="qr.state === 'Success' ? Success : Fail" class="img" />
                    {{ qr.state === "Success" ? "成功" : "失败" }}
                  </div>
                </div>
                <div style="flex: 1 1 100px;">
                  <MButton @click="deleteQr(index)" type="submit"
                    style="width: 50px;background: #F2F3F5;color: #4E5969;">
                    删除</MButton>
                  <MButton @click="identifyQe(qr, index)" type="submit" style="width: 50px;margin-left: 10px;">识别
                  </MButton>
                </div>

              </div>
            </div>
          </div>
        </div>

      </div>
    </div>

  </div>

</template>

<script>
import MButton from '../components/MButton.vue'
import QRCode from 'qrcode';
import { BrowserQRCodeReader } from '@zxing/library';
//import jsQR from 'jsqr';
import Success from "@/resource/success.png"
import Fail from "@/resource/error.png"
import html2canvas from 'html2canvas';
import { ref, } from 'vue';
export default {
  name: 'QrDestroy',
  props: {
    msg: String
  },
  components: {
    MButton,
  },
  data() {
    return {
      qrWidth: 260, // 二维码宽度
      qrHeight: 260, // 二维码高度
      drawing: false, // 是否正在绘制
      startX: 0, // 绘制起始X坐标
      startY: 0, // 绘制起始Y坐标
      qrInfo: '',
      isEdit: false,
      isMake: false,
      qrList: [],
      selectedLevel: "L",
      qrCodeUrl: "",
      blackRatio: 0,
      blackPixelsCanvas1: 0,
      blackPixelsCanvas2: 0,
      foregroundColor: '#000000', // 默认前景色
      backgroundColor: '#ffffff', // 默认背景色
      contrastInfo: 21,
      widthSize: "200",
      heightSize: "200",
      sizeContrast: 1,
    };
  },
  methods: {
    sizeChange() {
      this.sizeContrast = (Number(this.widthSize) / Number(this.heightSize)).toFixed(2)
    },
    colorChange() {
      this.contrastInfo = this.contrast(this.foregroundColor, this.backgroundColor)
    },
    contrast(hex1, hex2) {
      // 将hex颜色转为RGB
      const rgb1 = this.hexToRgb(hex1);
      const rgb2 = this.hexToRgb(hex2);

      // 计算亮度
      const L1 = this.luminance(rgb1.r, rgb1.g, rgb1.b);
      const L2 = this.luminance(rgb2.r, rgb2.g, rgb2.b);

      // 计算对比度
      const light = Math.max(L1, L2);
      const dark = Math.min(L1, L2);
      return ((light + 0.05) / (dark + 0.05)).toFixed(2);
    },
    hexToRgb(hex) {
      // 转换16进制颜色为RGB
      let r = 0, g = 0, b = 0;
      // 3位颜色值（例如 #fff）
      if (hex.length === 4) {
        r = parseInt(hex[1] + hex[1], 16);
        g = parseInt(hex[2] + hex[2], 16);
        b = parseInt(hex[3] + hex[3], 16);
      }
      // 6位颜色值（例如 #ff0000）
      else if (hex.length === 7) {
        r = parseInt(hex[1] + hex[2], 16);
        g = parseInt(hex[3] + hex[4], 16);
        b = parseInt(hex[5] + hex[6], 16);
      }
      return { r, g, b };
    },
    luminance(r, g, b) {
      // 将RGB转化为线性RGB
      let a = [r, g, b].map(function (v) {
        v /= 255;
        return (v <= 0.03928) ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
      });
      return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2];
    },
    handleAlertClosed() {
      // 这里可以处理弹窗关闭后的逻辑
      this.alertVisible = false;
    },
    async validateQRCode() {
      if (this.qrInfo !== "") {
        try {
          // 使用用户选择的颜色生成二维码
          const dataUrl = await QRCode.toDataURL(this.qrInfo, {
            errorCorrectionLevel: "L",
            color: {
              dark: this.foregroundColor,  // 前景色
              light: this.backgroundColor  // 背景色
            },
            margin: 2,
            width: 260,  // 设置二维码的宽度
            height: 260 // 设置二维码的高度
          });
          console.log(dataUrl);

          this.qrCodeUrl = dataUrl
        } catch (error) {
          console.error(error);
        }
      } else {

        alert("请输入内容")
      }

    },
    deleteQr(index) {
      this.qrList.splice(index, 1);
    },
    async identifyQe(qr, index) {
      const codeReader = new BrowserQRCodeReader();

      try {
        const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('解析超时')), 2000));

        // 使用 base64 数据解析二维码
        const result = await Promise.race([codeReader.decodeFromImage(undefined, qr.url), timeoutPromise]);

        if (result) {
          const a = [...this.qrList]
          a[index].state = "Success"
          this.qrList = a

        }
        else {
          const a = [...this.qrList]
          a[index].state = "Fail"
          this.qrList = a
        }
      } catch (error) {
        console.error('二维码解析失败', error);
        const a = [...this.qrList]
        a[index].state = "Fail"
        this.qrList = a
      }

    },

    save() {

      const tableElement = this.$refs.myImg; // 获取 table 元素
      html2canvas(tableElement, { scale: 2, }).then((canvas) => {
        // 将 canvas 转换为图片数据 URL
        const dataURL = canvas.toDataURL('image/png');
        this.qrList.push({
          info: this.qrInfo,
          url: dataURL,
          state: "",
          colorRatio: this.contrastInfo,
          whRatio: this.sizeContrast
        })
      });
    },
  },

  setup() {
    const imageRef = ref(null);
    return {
      Success,
      imageRef,
      Fail
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.listinfo {
  font-size: 12px;
  margin-top: 10px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  /* 设置显示的行数 */
  overflow: hidden;
  text-overflow: ellipsis;
}

.Success {
  width: 60px;
  height: 25px;
  font-size: 12px;
  text-align: center;
  margin-left: 10px;
  display: flex;
  align-items: center;
  color: #00B42A;
  background: #E8FFEA;
}

.Fail {
  width: 60px;
  height: 25px;
  font-size: 12px;
  background: #FFECE8;
  text-align: center;
  margin-left: 10px;
  display: flex;
  align-items: center;
  color: #F53F3F;
  ;
}

canvas {
  border: 1px solid #ccc;
  /* 可选，用于可视化边框 */
}

.img {
  width: 15px;
  height: 15px;
  margin: 0 5px;
}

.minput {
  height: 30px;
  border: 1px solid #ffffff;
  background: #F2F3F5;
  border-radius: 2px;
  box-sizing: border-box;
  padding: 0 5px;
}

.defaultTab {
  width: 70px;
  height: 24px;
  font-size: 12px;
  border-radius: 12px;
  color: #4E5969;
  background: white;
}

.selTab {
  width: 70px;
  height: 24px;
  background: #F2F3F8;
  font-size: 12px;
  border-radius: 12px;
  color: #1664FF;
}

.container_set {
  padding: 5px 20px;
}

.save {
  align-items: center;
  display: flex;
  justify-content: center;
  flex-direction: column;
  width: 70%;
  height: 20%;
}

.qrimg {
  width: 152px;
  height: 152px;
  border: 1px solid gray;
  margin-bottom: 5%;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.title {
  margin-bottom: 10px;
  text-align: left;
}

.qrleft {
  flex: 1 1 100px;
  text-align: left;
}

.qright {
  flex: 1 1 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.lcontainer {
  display: flex;
  padding: 10px;
  text-align: left;
}

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}


.card1 {
  width: 90%;
  height: 100%;
  margin-top: 10px;
  background: green;
  box-shadow: 0 8px 12px rgba(49, 49, 49, 0.3);
  border-radius: 5px;
  padding: 20px 20px 0 20px;
  background-color: white;
  transition: box-shadow 0.3s ease;
}

.card:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
  /* 鼠标悬停时加深阴影效果，营造悬浮起来的感觉 */
}

.card:last-child {
  margin-bottom: 0;

  /* 移除最后一个卡片的底部间距，使其符合要求 */
}

::-webkit-scrollbar {
  width: 5px;
  height: 5px;
  position: absolute;
}

::-webkit-scrollbar-thumb {
  background-color: #8d8c8c9d
}
</style>
